﻿using DB.From;
using DB.Main;
using Models;
using SqlSugar;

namespace WebApplication1.Models
{
    public class MysqlSugar
    {
        public SqlSugarScope DB { get; set; }

        public SqlSugarScope Main { get; set; }
        
        /// <summary>
        /// 连接到81服务器
        /// </summary>
        /// <param name="dataname"></param>
        public MysqlSugar(string dataname)
        {
            if(dataname == "FrontEnd4.0From")
            {
                DB = new SqlSugarScope(new ConnectionConfig()
                {
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    ConnectionString = $"server=192.168.100.13;database=FrontEnd4.0From;uid=pcmsadmin;password=111111_a"
                });
            }
            else
            {
                DB = new SqlSugarScope(new ConnectionConfig()
                {
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    ConnectionString = $"server=192.168.100.81;database={dataname};uid=pcmsadmin;password=111111_a"
                });
            }
            
            DB.Ado.CommandTimeOut = 30;

            Main = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                ConnectionString = $"server=192.168.100.13;database=FrontEnd4.0Main;uid=pcmsadmin;password=111111_a"
            });
            Main.Ado.CommandTimeOut = 30;
        }

        /// <summary>
        /// 测试是否连接成功
        /// </summary>
        /// <returns></returns>
        public bool IsConnect()
        {
            return DB.Ado.IsValidConnection();
        }

        /// <summary>
        /// 映射数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public bool MapData<T>(T model) where T : class,new()
        {
            var res = true;
            try
            {
                DB.Insertable<T>(model).ExecuteCommand();
            }catch (Exception ex) { 
                res = false;
            }

            return res;
        }

        /// <summary>
        /// 更新主库时间
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        public void UpdateTime(string TerminalId)
        {
            var find = Main.Queryable<t_Device>().Where(t=>t.TerminalId == TerminalId).OrderByDescending(t=>t.Id).First();

            if(find != null)
            {
                find.isOnline = true;
                find.LastDataTime = DateTime.Now;
                Main.Updateable(find).ExecuteCommand();
            }
        }
    }
}
